package com.etime.perfectschool.controller;

import com.etime.perfectschool.pojo.NewsPhoto;
import com.etime.perfectschool.service.NewsPhotoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;

@RestController
@CrossOrigin
public class NewsPhotoController {
    @Autowired
    private NewsPhotoService newsPhotoService;

    //添加新闻文件

    @PostMapping("/addNewsPhoto")
    public int insertNewsPhoto(MultipartFile[] file,int newsId)
    {
        System.out.println(newsId+"**********************");
        int i =0;
        String path = "D:\\perfectschool1\\src\\main\\resources\\static\\schoolnews";
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            for (MultipartFile multipartFile:file) {
                multipartFile.transferTo(new File(file1,multipartFile.getOriginalFilename()));
                String photoName = multipartFile.getOriginalFilename();
                System.out.println(photoName);
                NewsPhoto newsPhoto=new NewsPhoto(0,photoName,newsId);
                i = newsPhotoService.insertNewsPhoto(newsPhoto);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return i;
    }

    //删除指定新闻图片
    @DeleteMapping("/deleteNewsPhoto")
    public boolean deleteNewsPhotoById(int newsId)
    {
        return newsPhotoService.deleteNewsPhotoById(newsId);
    }
    //获取某条新闻的全部图片
    @GetMapping("/getAllNewsPhotoByNewsId")
    public List<NewsPhoto> getAllNewsPhotoByNewsId(int newsId) {
        return newsPhotoService.getAllNewsPhotoByNewsId(newsId);
    }
    //修改新闻图片
    @PutMapping("/updateNewsPhoto")
    public boolean updateNewsPhoto(MultipartFile[] file,int newsPhotoId)
    {
        System.out.println(":"+newsPhotoId);
        boolean i=false;
        String path = "D:\\pic";
        File file1 = new File(path);
        if (!file1.exists()) {
            file1.mkdirs();
        }
        try {
            for (MultipartFile multipartFile:file) {
                multipartFile.transferTo(new File(file1,multipartFile.getOriginalFilename()));
                String photoName = multipartFile.getOriginalFilename();
                NewsPhoto newsPhoto=new NewsPhoto(newsPhotoId,photoName,0);
                i = newsPhotoService.updateNewsPhoto(newsPhoto);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return i;
    }
}
